import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';

class LocaleViewModel extends ChangeNotifier {
  static const localeValueList = ['', 'zh-CN', 'en'];

  static const SP_KEY_LOCALE_INDEX = 'SP_KEY_LOCALE_INDEX';

  int _localeIndex;
  int get localeIndex => _localeIndex;

  Locale get locale {
    if (_localeIndex > 0) {
      var value = localeValueList[_localeIndex].split('-');
      return Locale(value[0], value.length == 2 ? value[1] : '');
    }
    return null;
  }

  //构造函数，初始化 _localeIndex,不让应用启动会报空指针异常
  LocaleViewModel() {
    _localeIndex = SpUtil.getInt(SP_KEY_LOCALE_INDEX);
    switchLocale(_localeIndex);
  }

  //切换语言
  switchLocale(int index) {
    _localeIndex = index;
    SpUtil.putInt(SP_KEY_LOCALE_INDEX, index);
    notifyListeners();
  }
}
